<template>
  <div class="createPost-container">
    <el-form ref="postForm" :model="postForm" :rules="rules" class="form-container">
      <sticky :z-index="10" :class-name="'sub-navbar '+postForm.status">
        <el-button v-loading="loading" style="margin-left: 10px;" type="success" @click="submitForm">
          发布
        </el-button>
        <el-button v-loading="loading" type="warning" @click="draftForm">
          保存草稿
        </el-button>
      </sticky>

      <div class="createPost-main-container">
        <el-row>
          <Warning />
          <el-col :span="24">
            <el-form-item style="margin-bottom: 40px;" prop="title">
              <MDinput v-model="postForm.title" :maxlength="100" name="name" required>
                标题
              </MDinput>
            </el-form-item>

            <el-form-item prop="img" style="margin-bottom: 40px;">
              <MDinput v-model="postForm.img" :maxlength="100" name="name" required>
                封面
              </MDinput>
              <el-collapse>
                <el-collapse-item title="推荐的封面" name="1">
                  <div style="margin-bottom: 10px;">
                    <el-tooltip content="刷新图片" placement="right" effect="dark">
                      <el-button :loading="isInit" size="mini" type="primary" icon="el-icon-refresh-right" round @click="init()"></el-button>
                    </el-tooltip>
                  </div>
                  <el-tooltip :content="url" v-for="url in urls.imgs" :key="url" placement="bottom" effect="dark">
                    <el-image class="margin:5px;" style="width: 200px; height: 100px" :src="url" fit="contain" @click="setImg(url)"></el-image>
                  </el-tooltip>
                </el-collapse-item>
              </el-collapse>
            </el-form-item>

            <el-form-item prop="banner" style="margin-bottom: 40px;">
              <MDinput v-model="postForm.banner" :maxlength="100" name="name" required>
                背景
              </MDinput>
              <el-collapse>
                <el-collapse-item title="推荐的背景" name="1">
                  <div style="margin-bottom: 10px;">
                    <el-tooltip content="刷新图片" placement="right" effect="dark">
                      <el-button :loading="isInit" size="mini" type="primary" icon="el-icon-refresh-right" round @click="init()"></el-button>
                    </el-tooltip>
                  </div>
                  <el-tooltip :content="url" v-for="url in urls.banners" :key="url" placement="bottom" effect="dark">
                    <el-image class="margin:5px;" style="width: 200px; height: 100px" :src="url" fit="contain" @click="setBanner(url)"></el-image>
                  </el-tooltip>
                </el-collapse-item>
              </el-collapse>
            </el-form-item>


            <div class="postInfo-container">
              <el-row>
                <el-col :span="4">
                  <el-form-item label-width="60px" label="作者:" class="postInfo-container-item">
                    <span>{{user.name}}</span>
                    <!--                    <el-select v-model="postForm.author" :remote-method="getRemoteUserList" filterable default-first-option remote placeholder="Search user">
                      <el-option v-for="(item,index) in userListOptions" :key="item+index" :label="item" :value="item" />
                    </el-select> -->
                  </el-form-item>
                </el-col>

                <el-col :span="4">
                  <el-form-item prop="type" label-width="60px" label="标签:" class="postInfo-container-item">
                    <el-popover ref="tag" placement="right" title="[管理] 已有标签" width="400" trigger="focus">
                      <!-- <div style="margin-bottom: 10px;"> -->
                      <el-tooltip content="[同步] 数据刷新可能有延迟,请耐心等待,不要频繁操作!" placement="left" effect="dark" style="margin-right: 10px;">
                        <el-button :loading="isInit" size="small" type="primary" icon="el-icon-refresh-right" @click="init()"></el-button>
                      </el-tooltip>
                      <!-- </div> -->
                      <el-tag :key="tag" v-for="tag in options.concat(addTypes)" closable :disable-transitions="false"
                        @close="open(tag)">
                        {{tag}}
                      </el-tag>
                      <el-input class="input-new-tag" v-if="inputVisible" v-model="inputValue" ref="saveTagInput" size="small"
                        @keyup.enter.native="handleInputConfirm" @blur="handleInputConfirm">
                      </el-input>
                      <el-button v-else class="button-new-tag" size="small" @click="showInput">+ 新标签</el-button>
                    </el-popover>
                    <el-select v-model="postForm.type" placeholder="请选择" v-popover:tag>
                      <el-option v-for="item in options" :key="item" :label="item" :value="item">
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>

                <el-col :span="10">
                  <el-form-item label-width="120px" label="发布时间:" class="postInfo-container-item">
                    <el-date-picker v-model="displayTime" type="datetime" format="yyyy-MM-dd HH:mm:ss" placeholder="选择发布时间" />
                  </el-form-item>
                </el-col>

                <el-col :span="6">
                  <el-form-item label-width="90px" label="重要性:" class="postInfo-container-item">
                    <el-rate v-model="postForm.importance" :max="2" :colors="['#99A9BF', '#F7BA2A', '#FF9900']"
                      :low-threshold="1" :high-threshold="2" style="display:inline-block" :texts="texts" show-text/>
                  </el-form-item>
                </el-col>
<!--                <el-col :span="4">
                <template>
                  <el-radio v-model="postForm.comment_disabled" label="false">备选项</el-radio>
                  <el-radio v-model="postForm.comment_disabled" label="true">备选项</el-radio>
                </template>
                 </el-col> -->
              </el-row>
            </div>
          </el-col>
        </el-row>

        <el-form-item style="margin-bottom: 40px;" label-width="70px" label="概要:">
          <el-input v-model="postForm.summary" :rows="1" type="textarea" class="article-textarea" autosize
            placeholder="简短的描述文章主题" />
          <span v-show="contentShortLength" class="word-counter">{{ contentShortLength }}字</span>
        </el-form-item>

        <el-form-item prop="content" style="margin-bottom: 30px;">
          <Tinymce ref="editor" v-model="postForm.content" :height="400" />
        </el-form-item>

        <!--        <el-form-item prop="img" style="margin-bottom: 30px;">
          <Upload v-model="postForm.img" />
        </el-form-item> -->
      </div>
    </el-form>
  </div>
</template>

<script>
  import Tinymce from '@/components/Tinymce'
  import Upload from '@/components/Upload/SingleImage3'
  import MDinput from '@/components/MDinput'
  import Sticky from '@/components/Sticky' // 粘性header组件
  import {htmlDecode} from '../../../utils/index.js'
  import {
    htmlEncode
  } from '../../../utils/index.js'
  import {
    getUrls,
    updateType,
    deleteType,
    addType,
    saveDoc,
    fetchArticle
  } from '../../../api/doc.js'
  import {
    validURL
  } from '@/utils/validate'
  import {
    searchUser
  } from '@/api/remote-search'
  import {
    mapGetters
  } from 'vuex'

  import Warning from './Warning'
  import {
    CommentDropdown,
    PlatformDropdown,
    SourceUrlDropdown
  } from './Dropdown'

  const defaultForm = {
    status: 'draft',
    title: '', // 文章题目
    content: '', // 文章内容
    summary: '', // 文章摘要
    source_uri: '', // 文章外链
    displayTime: undefined, // 前台展示时间
    id: undefined,
    // platforms: ['a-platform'],
    comment_disabled: true,
    importance: 1,
    img: '',
    banner: '',
    comment: 0,
    type: '',
    viewCount: 0,
  }

  export default {
    name: 'ArticleDetail',
    components: {
      Tinymce,
      MDinput,
      Upload,
      Sticky,
      Warning,
      CommentDropdown,
      PlatformDropdown,
      SourceUrlDropdown
    },
    props: {
      isEdit: {
        type: Boolean,
        default: false
      }
    },
    data() {

      const validateRequire = (rule, value, callback) => {
        if (value === '') {
          this.$message({
            message: rule.field + '为必传项',
            type: 'error'
          })
          callback(new Error(rule.field + '为必传项'))
        } else {
          callback()
        }
      }
      const validateSourceUri = (rule, value, callback) => {
        if (value) {
          if (validURL(value)) {
            callback()
          } else {
            this.$message({
              message: 'url填写不正确',
              type: 'error'
            })
            callback(new Error('url填写不正确'))
          }
        } else {
          callback()
        }
      }
      return {
        texts:['普通','顶置'],
        addTypes: [],
        inputVisible: false,
        inputValue: '',
        isInit: false,
        urls: [
          'https://fuss10.elemecdn.com/a/3f/3302e58f9a181d2509f3dc0fa68b0jpeg.jpeg',
          'https://fuss10.elemecdn.com/1/34/19aa98b1fcb2781c4fba33d850549jpeg.jpeg',
          'https://fuss10.elemecdn.com/0/6f/e35ff375812e6b0020b6b4e8f9583jpeg.jpeg',
          'https://fuss10.elemecdn.com/9/bb/e27858e973f5d7d3904835f46abbdjpeg.jpeg',
          'https://fuss10.elemecdn.com/d/e6/c4d93a3805b3ce3f323f7974e6f78jpeg.jpeg',
          'https://fuss10.elemecdn.com/3/28/bbf893f792f03a54408b3b7a7ebf0jpeg.jpeg',
          'https://fuss10.elemecdn.com/2/11/6535bcfb26e4c79b48ddde44f4b6fjpeg.jpeg'
        ],
        options: [],
        user: {},
        postForm: Object.assign({}, defaultForm),
        loading: false,
        userListOptions: [],
        rules: {
          img: [{
            validator: validateRequire
          }],
          banner: [{
            validator: validateRequire
          }],
          title: [{
            validator: validateRequire
          }],
          type:[{
            validator: validateRequire
          }],
          content: [{
            validator: validateRequire
          }],
          source_uri: [{
            validator: validateSourceUri,
            trigger: 'blur'
          }]
        },
        tempRoute: {}
      }
    },
    computed: {
      ...mapGetters([
        'name',
        'avatar',
        'roles'
      ]),
      contentShortLength() {
        return this.postForm.summary.length
      },
      lang() {
        return this.$store.getters.language
      },
      displayTime: {
        // set and get is useful when the data
        // returned by the back end api is different from the front end
        // back end return => "2013-06-25 06:59:25"
        // front end need timestamp => 1372114765000
        get() {
          return (+new Date(this.postForm.displayTime))
        },
        set(val) {
          this.postForm.displayTime = new Date(val)
        }
      }
    },
    created() {
      this.init()
      if (this.isEdit) {
        const id = this.$route.params && this.$route.params.id
        this.fetchData(id)
      }
      this.getUser()
      // Why need to make a copy of this.$route here?
      // Because if you enter this page and quickly switch tag, may be in the execution of the setTagsViewTitle function, this.$route is no longer pointing to the current page
      // https://github.com/PanJiaChen/vue-element-admin/issues/1221
      this.tempRoute = Object.assign({}, this.$route)
    },
    methods: {
      open(tag) {
        const h = this.$createElement;
        this.$msgbox({
          title: '提示',
          message: '删除标签会置空所有被\"' + tag + '\"标记文章的标签，建议您修改此标签',
          showInput: true,
          inputValue: tag,
          type: 'warning',
          confirmButtonText: '修改',
          cancelButtonText: '继续删除',
          showCancelButton: true,
          distinguishCancelAndClose: true,
          beforeClose: async (action, instance, done) => {
            if (action === 'confirm') {
              instance.confirmButtonLoading = true;
              instance.confirmButtonText = '执行中...';
              // 修改
              if (instance.inputValue === '') {
                instance.confirmButtonLoading = false;
                done();
              } else {
                await updateType({
                  key: tag,
                  value: instance.inputValue
                }).then(res => {
                  instance.confirmButtonLoading = false;
                  instance.confirmButtonText = '修改';
                  if (res.code == 20000) {
                    // 更新当前数据
                    for (let i = 0; i < this.options.length; i++) {
                      if (this.options[i] == tag) {
                        this.options[i] = instance.inputValue;
                        break;
                      }
                      this.postForm.type = '';
                    }
                    this.$message({
                      type: 'success',
                      message: res.data
                    });
                    done();
                  } else {
                    done();
                  }
                }).catch(res => {
                  instance.confirmButtonLoading = false;
                  instance.confirmButtonText = '修改';
                });
              }

            } else if (action === 'cancel') {
              // 删除操作
              await deleteType({
                key: tag,
                value: '',
              }).then(res => {
                if (res.code === 20000) {
                  this.postForm.type = '';
                  // 更新当前数据
                  this.handleClose(tag)
                  this.$message({
                    type: 'success',
                    message: res.data
                  });
                }
                done();
              }).catch(res => {});
              done();
            } else {
              this.$message({
                type: 'info',
                message: '取消操作'
              });
              done();
            }
          }
        }).then(action => {}).catch(action => {});
      },
      handleClose(tag) {
        // 删除
        this.options.splice(this.options.indexOf(tag), 1);
        // 增加数组中也要删除
        this.addTypes.splice(this.addTypes.indexOf(tag), 1);

      },
      showInput() {
        this.inputVisible = true;
        this.$nextTick(_ => {
          this.$refs.saveTagInput.$refs.input.focus();
        });
      },
      // /添加标签
      handleInputConfirm() {
        let inputValue = this.inputValue;
        if (inputValue) {
          // 只添加到add
          // this.options.push(inputValue);
          this.addTypes.push(inputValue);
        }
        this.inputVisible = false;
        this.inputValue = '';
        if (inputValue !== '') {
          this.init()
        }

      },
      init: async function() {
        this.isInit = true
        if (this.addTypes.length !== 0) {
          await addType(this.addTypes).then(res => {
            if (res.code === 20000) {
              // 加入options
              this.options = this.options.concat(this.addTypes)
              // 清空数组
              // 危！ this.addTypes.length = 0
              this.addTypes = [];
              this.$message({
                message: res.data,
                type: 'success',
                showClose: true,
                duration: 1000
              })
            }
          }).catch(res => {
            this.isInit = false
          })
        }
        getUrls().then(res => {
          if (res.code !== 20000) {} else {
            this.urls = res.data
            this.options = res.data.types
          }
          this.isInit = false
        }).catch(res => {
          this.isInit = false
        })
      },
      setImg(url) {
        this.postForm.img = url
      },
      setBanner(url) {
        this.postForm.banner = url
      },
      getUser() {
        this.user = {
          name: this.name,
          role: this.roles.join(' | '),
          email: 'admin@test.com',
          avatar: this.avatar
        }
      },
      fetchData(id) {
        fetchArticle(id).then(response => {
          this.postForm = response.data
          this.postForm.content = htmlDecode(response.data.content)
          this.postForm.banner = response.data.background;
          // just for test
          // this.postForm.title += `   Article Id:${this.postForm.id}`
          // this.postForm.summary += `   Article Id:${this.postForm.id}`

          // set tagsview title
          this.setTagsViewTitle()

          // set page title
          this.setPageTitle()
        }).catch(err => {
          console.log(err)
        })
      },
      setTagsViewTitle() {
        const title = this.lang === 'zh' ? '编辑文章' : 'Edit Article'
        const route = Object.assign({}, this.tempRoute, {
          title: `${title}-${this.postForm.id}`
        })
        this.$store.dispatch('tagsView/updateVisitedView', route)
      },
      setPageTitle() {
        const title = 'Edit Article'
        document.title = `${title} - ${this.postForm.id}`
      },
      submitForm: function() {
        if (this.postForm.type.length === 0 ) {
          this.$message({
            message: '请填写必要的标签',
            type: 'warning'
          })
          return
        }
        this.$refs.postForm.validate(valid => {
          if (valid) {
            this.loading = true
            this.postForm.status = 'published'
            saveDoc(this.getDoc('published')).then(res => {
              if (res.code === 20000) {
                this.postForm.id = res.data;
                this.$notify({
                  title: '成功',
                  message: res.msg,
                  type: 'success',
                  duration: 2000
                })
              }
            }).catch(res => {});
            this.loading = false
          } else {
            console.log('error submit!!')
            return false
          }
        })
      },
      draftForm: async function() {
        if (this.postForm.content.length === 0 || this.postForm.title.length === 0 || this.postForm.type.length === 0) {
          this.$message({
            message: '请填写必要的标题,标签和内容',
            type: 'warning'
          })
          return
        }
        this.postForm.status = 'draft'
        await saveDoc(this.getDoc('draft')).then(res => {
          if (res.code === 20000) {
            this.postForm.id = res.data;
            this.$notify({
              title: '成功',
              message: res.msg,
              type: 'success',
              duration: 2000
            })
          }
        }).catch(res => {});
      },
      getDoc(status) {
        // const time = this.postForm.displayTime.getTime();
        if (this.postForm.displayTime instanceof Object) {
          this.postForm.displayTime = this.postForm.displayTime.getTime();
        }
        const doc = {
          id: this.postForm.id,
          title: this.postForm.title,
          content: htmlEncode(this.postForm.content),
          viewCount: this.postForm.viewCount,
          lastTime: new Date().getTime(),
          displayTime: this.postForm.displayTime,
          author: this.user.name,
          summary: this.postForm.summary,
          importance: this.postForm.importance,
          type: this.postForm.type,
          status: status,
          img: this.postForm.img,
          background: this.postForm.banner,
          comment: this.postForm.comment_disabled ? -Math.abs(this.postForm.comment) : Math.abs(this.postForm.comment),
        }
        return doc;
      },
      getRemoteUserList(query) {
        searchUser(query).then(response => {
          if (!response.data.items) return
          this.userListOptions = response.data.items.map(v => v.name)
        })
      }
    }
  }
</script>

<style lang="scss" scoped>
  @import "~@/styles/mixin.scss";

  .el-tag+.el-tag {
    margin-left: 10px;
  }

  .button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
  }

  .input-new-tag {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
  }

  .createPost-container {
    position: relative;

    .createPost-main-container {
      padding: 40px 45px 20px 50px;

      .postInfo-container {
        position: relative;
        @include clearfix;
        margin-bottom: 10px;

        .postInfo-container-item {
          float: left;
        }
      }
    }

    .word-counter {
      width: 40px;
      position: absolute;
      right: 10px;
      top: 0px;
    }
  }

  .article-textarea ::v-deep {
    textarea {
      padding-right: 40px;
      resize: none;
      border: none;
      border-radius: 0px;
      border-bottom: 1px solid #bfcbd9;
    }
  }
</style>
